//
//  ViewController.m
//  03地图定位
//
//  Created by 张聪 on 16/7/16.
//  Copyright © 2016年 张聪. All rights reserved.
//

#import "ViewController.h"
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>
#import "Masonry.h"
#import "ZCAnnotaion.h"
#import "ZCAnnotationView.h"
#import "ZCBestViewController.h"
#import "ZCNavView.h"
#import "ZCControlView.h"


@interface ViewController ()<MKMapViewDelegate>

//位置管理者
@property (nonatomic, strong) CLLocationManager *manager;

@property (nonatomic, strong) MKMapView *mapView;

//@property (nonatomic, strong) UISegmentedControl *segmenteControl;

@property (nonatomic, assign) BOOL isDaTou;

//@property (nonatomic, strong) UIButton *daTouBtn;

//@property (nonatomic, strong) UITextField *endTextField;

//@property (nonatomic, strong) UIButton *blackBtn;
//@property (nonatomic, strong) UIButton *bigBtn;
//@property (nonatomic, strong) UIButton *smallBtn;
//@property (nonatomic, strong) UILabel *navLabel;
//@property (nonatomic, strong) UIButton *navBtn;

//@property (nonatomic, strong) UISegmentedControl *segmenteControl;

@property (nonatomic, strong) ZCNavView *navView;
@property (nonatomic, strong) ZCControlView *controlView;

@property (nonatomic, strong) ZCAnnotationView *annotations;
//

@end


@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
//    self.isDaTou = YES;
    
    [self settingUI];
    
    [self settingMap];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didNavBtnClick) name:@"didNavBtnClicks" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didSegmenteClick:) name:@"didSegmenteClicks" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didBlackClick) name:@"didBlackClick" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didBigBtnClick) name:@"didBigBtnClick" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didSmallBtnClick) name:@"didSmallBtnClick" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didDaTouClick) name:@"didDaTouClicks" object:nil];
    
    
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    self.mapView.delegate = nil;
    self.mapView = nil;
    [self.mapView removeFromSuperview];
    NSLog(@"...");
}

- (void)didNavVc {

    [self.navigationController popToRootViewControllerAnimated:YES];
    
    
}

- (void)settingUI {
    
    //创建管理者
    self.manager = [[CLLocationManager alloc] init];
    
    //开启位置请求授权
    if ([self.manager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
        //设置plist文件
        [self.manager requestWhenInUseAuthorization];
    }
    
    ZCNavView *navView = [[ZCNavView alloc] init];
    self.navView = navView;
    [self.view addSubview:navView];
    
    [navView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(64);
        make.leading.equalTo(self.view);
        make.trailing.equalTo(self.view);
        make.height.mas_equalTo(40);
        
    }];
    
    
    ZCControlView *controlView = [[ZCControlView alloc] init];
    self.controlView = controlView;
    [self.view addSubview:controlView];
    
    [controlView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view);
        make.leading.equalTo(self.view);
        make.trailing.equalTo(self.view);
        make.height.mas_equalTo(120);
    }];
    
    
    //创建地图view
    MKMapView *mapView = [[MKMapView alloc] init];
    self.mapView = mapView;
    
    //CGRectMake(CGFloat x, <#CGFloat y#>, <#CGFloat width#>, <#CGFloat height#>)
//    self.mapView.frame = self.view.frame;
    [self.view addSubview:self.mapView];
    
    mapView.frame = CGRectMake(0, navView.frame.size.height + 64, self.view.frame.size.width, self.view.frame.size.height - navView.frame.size.height - controlView.frame.size.height - 64);
    
    //设置定位 设置地图的用户跟踪模式
    self.mapView.userTrackingMode = MKUserTrackingModeFollow;
    
    //大头针视图是由系统来添加的,可以通过设置大头针模型来设置大头针视图的数据  MKUserLocation是定位大头针的模型类
    self.mapView.delegate = self;
    
}

#pragma mark - 懒加载
- (MKMapView *)mapView {
    if (_mapView == nil) {
        _mapView = [[MKMapView alloc] init];
    }
    
    return _mapView;
}





- (void)settingMap {
    //设置标尺
    self.mapView.showsScale = YES;
    
    //设置罗盘
    self.mapView.showsCompass = YES;
    
    //显示交通
    self.mapView.showsTraffic = YES;
    
    //设置3d模式
    self.mapView.showsBuildings = YES;
    
    //设置航拍模式
    ///
    ///(fromDistance)航拍飞机的线
    ///pitch角度
    ///heading朝向
//    self.mapView.camera = [MKMapCamera cameraLookingAtCenterCoordinate:self.mapView.userLocation.location.coordinate fromDistance:100 pitch:65 heading:0];
    
    //是否定位用户
    self.mapView.showsUserLocation = YES;
    
    //设置感兴趣的店
    self.mapView.showsPointsOfInterest = YES;
    
    
    
}



#pragma mark - 添加自定义大头针
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    if (self.isDaTou == NO) {
        return;
    }
    
    //创建自定义大头针模型并生成对象  所有遵守MKAnnotation协议的类都可以作为大头针模型类
    ZCAnnotaion *annotaion = [[ZCAnnotaion alloc] init];
    
    //设置数据
    //设置经纬度 MapView中提供了iOS坐标和经纬度之间的转换方式
    //获取ios坐标
    UITouch *touch = touches.anyObject;
    CGPoint point = [touch locationInView:self.mapView];
    
    annotaion.coordinate = [self.mapView convertPoint:point toCoordinateFromView:self.mapView];
    

         //设置标题
    annotaion.title = @"哈哈哈";
    annotaion.subtitle = @"seccess";
    
    //添加模型
    [self.mapView addAnnotation:annotaion];
    
    
}


#pragma mark - 内存优化
- (void)applyMapViewMemoryHotFix{
    
    switch (self.mapView.mapType) {
        case MKMapTypeHybrid://混合
        {
            
            self.mapView.mapType = MKMapTypeHybrid;
        }
            
            break;
        case MKMapTypeStandard://标准
        {
          
            self.mapView.mapType = 11;
            self.mapView.mapType = MKMapTypeStandard;
            
            
        }
            
            break;
        case MKMapTypeSatellite://标准卫星
        {
            
           
            
            self.mapView.mapType = MKMapTypeSatellite;
        }
            
            break;
        case MKMapTypeSatelliteFlyover://标准卫星
        {
            
            
            self.mapView.mapType = MKMapTypeSatelliteFlyover;
        }
            
            break;
        case MKMapTypeHybridFlyover://鸟瞰
        {
           
            
            self.mapView.mapType = MKMapTypeHybridFlyover;
        }
            
            break;
          
            
            
        default:
            break;
    }
    
}


#pragma mark - MKMapViewDelegate
//- (void)mapView:(MKMapView *)mapView regionWillChangeAnimated:(BOOL)animated {
//    
//    [self applyMapViewMemoryHotFix];
//
//    
//}

//内存释放的代理方法
- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated {
    
    if (self.mapView != nil) {
        [self.mapView removeFromSuperview];
    }
    [self.view addSubview:self.mapView];
    [self applyMapViewMemoryHotFix];
    
}


/// 当设置覆盖物的样式时调用
///
/// @param mapView 地图视图
/// @param overlay 地图覆盖物
///
/// @return 地图覆盖物样式
- (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id<MKOverlay>)overlay {
    
    //    //设置折线的样式需要使用子类MKPolylineRenderer
    
    MKPolylineRenderer *renderer = [[MKPolylineRenderer alloc] initWithOverlay:overlay];
    //设置属性
    renderer.lineWidth = 3.0;
    renderer.strokeColor = [UIColor redColor];
    
    
    return renderer;
    
}





/// 当设置大头针视图的大头针模型时调用,该方法还是大头针视图重用的设置方法
///
/// @param mapView    地图视图
/// @param annotation 大头针视图对应的大头针模型
///
/// @return 大头针视图
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation {
    
    
    //过滤大头针
    if ([annotation isKindOfClass:[MKUserLocation class]]) {
        return nil;
    }
    
    
    self.annotations = [ZCAnnotationView annoWithMapView:self.mapView];
    
    return self.annotations;
}

/// 当已经添加大头针视图后调用(此时大头针视图的位置已经确定,但是还没有显示),该方法专门用于设置大头针视图的动画
///
/// @param mapView 地图视图
/// @param views   数组<已经添加的大头针视图>
- (void)mapView:(MKMapView *)mapView didAddAnnotationViews:(NSArray<MKAnnotationView *> *)views {
    
    //遍历大头针模型
    for (MKAnnotationView *annoV in views) {
        
        //记录当前位置
        CGRect taget = annoV.frame;
        //修改大头针位置
        annoV.frame = CGRectMake(taget.origin.x, 0, taget.size.width, taget.size.height);
        //执行动画
        [UIView animateWithDuration:0.5 animations:^{
            annoV.frame = taget;
            
            
        }];
        
        
    }
    
    
    
    
    
}



//更新地图调用
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation {
    
    //创建地理编码者
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    
    //反地理编码 地理->人文
    [geocoder reverseGeocodeLocation:userLocation.location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        
        //判断地标对象是不是0
        if (placemarks.count == 0 || error) {
            return;
        }
        
        CLPlacemark *pm = placemarks.lastObject;
        //城市
        self.mapView.userLocation.title = pm.locality;
        //具体名称
        self.mapView.userLocation.subtitle = pm.name;
        
    
        
    }];
    
}


#pragma mark - 事件响应:

//导航
-(void)didNavBtnClick {
    //自定义地图导航 : 将起点和终点发送给apple服务器,服务器进行路线计算,然后将查询结果返回给客户端,进行界面展示
    //创建请求
    MKDirectionsRequest *request = [[MKDirectionsRequest alloc] init];
    
    //设置起点
    request.source = [MKMapItem mapItemForCurrentLocation];
    
    //设置终点 通过地理编码者获取地标对象
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    //地理编码
    [geocoder geocodeAddressString:self.navView.endTextField.text completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        
        CLPlacemark *clpm = placemarks.lastObject;
        
        MKPlacemark *pm = [[MKPlacemark alloc] initWithPlacemark:clpm];
        
        //终点destination需要依靠Placemark来穿件
        request.destination = [[MKMapItem alloc] initWithPlacemark:pm];
        
        //创建导航对象
        MKDirections *directions = [[MKDirections alloc] initWithRequest:request];
        
        
        //请求服务器计算路线
        [directions calculateDirectionsWithCompletionHandler:^(MKDirectionsResponse * _Nullable response, NSError * _Nullable error) {
            
            //路线对象MKRoute遍历
            for (MKRoute *route in response.routes) {
                //                for (MKRouteStep *step in route.steps) {
                //                    NSLog(@"%@", step.instructions);
                //                }
                
                //添加路线折线  折线属于地图覆盖物  所有遵守MKOverlay协议的类都可以作为地图覆盖物
                
                [self.mapView addOverlay:route.polyline];
                
            }
            
        }];
    }];
    
    [self.view endEditing:YES];

}


////大头针
- (void)didDaTouClick {
    
    if (self.isDaTou == YES) {
    [self.controlView.daTouBtn setTitle:@"开启大头针" forState:UIControlStateNormal];
        
        self.isDaTou = NO;
      
        return;
        
    }
    
    
    if (self.isDaTou == NO) {
        
        [self.controlView.daTouBtn setTitle:@"关闭大头针" forState:UIControlStateNormal];
    
        
        
        
        self.isDaTou = YES;
        
    }


}


//放大
- (void)didBigBtnClick {
    //获取中心点
    CLLocationCoordinate2D center = self.mapView.region.center;
    
    //设置跨度
    MKCoordinateSpan span = MKCoordinateSpanMake(self.mapView.region.span.latitudeDelta * 0.5, self.mapView.region.span.longitudeDelta * 0.5);
    
    
    //设置范围
    [self.mapView setRegion:MKCoordinateRegionMake(center, span) animated:YES];
    
    
    
}

//缩小
- (void)didSmallBtnClick {
    CLLocationDegrees deg = self.mapView.region.span.latitudeDelta;
    
    
    //获取中心点
    CLLocationCoordinate2D center = self.mapView.region.center;
    
    
    
    //设置跨度
    MKCoordinateSpan span = MKCoordinateSpanMake(deg, self.mapView.region.span.longitudeDelta * 2.0);
    
    
    
    
    
    //设置范围
    [self.mapView setRegion:MKCoordinateRegionMake(center, span) animated:YES];
    
    
}

//点击了SegmenteClick
- (void)didSegmenteClick:(NSNotification *)info {
    
//    MKMapTypeStandard = 0,
//    MKMapTypeSatellite,
//    MKMapTypeHybrid,
//    MKMapTypeSatelliteFlyover NS_ENUM_AVAILABLE(10_11, 9_0),
//    MKMapTypeHybridFlyover NS_ENUM_AVAILABLE(10_11, 9_0),
    
    switch ([info.userInfo[@"segmentKey"] integerValue]) {
        case 0:
            self.mapView.mapType = MKMapTypeStandard;
            break;
        case 1:
            self.mapView.mapType = MKMapTypeSatellite;
            break;
        case 2:
            self.mapView.mapType = MKMapTypeHybrid;
            break;
        case 3:
            self.mapView.mapType = MKMapTypeSatelliteFlyover;
            break;
        case 4:
            self.mapView.mapType = MKMapTypeHybridFlyover;
            break;
            
        default:
            break;
    }
    
    
    
}

//返回
- (void)didBlackClick {
    
    //1.重新定位
//    [self.mapView setUserTrackingMode:MKUserTrackingModeFollow animated:YES];
    
    //2.设置地图范围
    //设置中心点
    CLLocationCoordinate2D center = self.mapView.userLocation.location.coordinate;
    
    //设置span跨度,region(范围)
    MKCoordinateSpan span = self.mapView.region.span;
    
    [self.mapView setRegion:MKCoordinateRegionMake(center, span) animated:YES];
    
}

- (void)dealloc {
    
    [self.mapView removeFromSuperview];
    
    self.mapView.delegate = nil;
    
    self.mapView = nil;
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    NSLog(@"我销毁了");
    
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}




@end
